<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>完整购物车功能</title>
    <style>
        :root {
            --primary-color: #007bff;
            --danger-color: #dc3545;
            --success-color: #28a745;
        }
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', sans-serif;
        }
        body {
            padding: 2rem;
            background-color: #f8f9fa;
        }
        .container {
            max-width: 1000px;
            margin: 0 auto;
        }
        .product-list {
            display: grid;
            gap: 1.5rem;
            margin-bottom: 2rem;
        }
        .product-card {
            background: white;
            padding: 1.5rem;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            display: flex;
            align-items: center;
            gap: 1.5rem;
        }
        .product-image {
            width: 120px;
            height: 120px;
            object-fit: cover;
            border-radius: 4px;
        }
        .product-info {
            flex: 1;
        }
        .quantity-control {
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        .quantity-input {
            width: 60px;
            padding: 0.5rem;
            text-align: center;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .btn {
            padding: 0.5rem 1rem;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            transition: opacity 0.3s;
        }
        .btn-primary {
            background-color: var(--primary-color);
            color: white;
        }
        .btn-danger {
            background-color: var(--danger-color);
            color: white;
        }
        .btn-success {
            background-color: var(--success-color);
            color: white;
            padding: 1rem 2rem;
        }
        .cart-list {
            background: white;
            border-radius: 8px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        .cart-item {
            display: flex;
            align-items: center;
            padding: 1rem 0;
            border-bottom: 1px solid #eee;
        }
        .cart-item:last-child {
            border-bottom: none;
        }
        .total-price {
            font-size: 1.5rem;
            color: var(--success-color);
            font-weight: bold;
            text-align: right;
            padding: 1rem;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="product-list">
            <!-- 商品列表 -->
            <div class="product-card">
                <img src="img/product-image1.jpg" class="product-image" alt="商品A">
                <div class="product-info">
                    <h3>商品A</h3>
                    <p>价格：¥99.00</p>
                </div>
                <div class="quantity-control">
                    <input type="number" class="quantity-input" value="1" min="1">
                    <button class="btn btn-primary add-to-cart" 
                            data-id="1" 
                            data-name="商品A" 
                            data-price="99">
                        加入购物车
                    </button>
                </div>
            </div>
            <div class="product-card">
                <img src="img/product-image2.jpg" class="product-image" alt="商品B">
                <div class="product-info">
                    <h3>商品B</h3>
                    <p>价格：¥199.00</p>
                </div>
                <div class="quantity-control">
                    <input type="number" class="quantity-input" value="1" min="1">
                    <button class="btn btn-primary add-to-cart" 
                            data-id="2" 
                            data-name="商品B" 
                            data-price="199">
                        加入购物车
                    </button>
                </div>
            </div>
            <div class="product-card">
                <img src="img/product-image3.jpg" class="product-image" alt="商品C">
                <div class="product-info">
                    <h3>商品C</h3>
                    <p>价格：¥299.00</p>
                </div>
                <div class="quantity-control">
                    <input type="number" class="quantity-input" value="1" min="1">
                    <button class="btn btn-primary add-to-cart" 
                            data-id="3" 
                            data-name="商品C" 
                            data-price="299">
                        加入购物车
                    </button>
                </div>
            </div>
            <div class="product-card">
                <img src="img/product-image4.jpg" class="product-image" alt="商品D">
                <div class="product-info">
                    <h3>商品D</h3>
                    <p>价格：¥399.00</p>
                </div>
                <div class="quantity-control">
                    <input type="number" class="quantity-input" value="1" min="1">
                    <button class="btn btn-primary add-to-cart" 
                            data-id="4" 
                            data-name="商品D" 
                            data-price="399">
                        加入购物车
                    </button>
                </div>
            </div>
        </div>
        <!-- 购物车区域 -->
        <div class="cart-list">
            <h2>购物车</h2>
            <div id="cartItems"></div>
        </div>
        
        <div class="total-price">
            总价：¥<span id="totalPrice">0.00</span>
        </div>
        <div class="text-right">
            <button class="btn btn-success" id="checkout">立即结算</button>
        </div>
    </div>
    <script>
        // 初始化购物车
        let cart = loadCartFromStorage();
        // 页面加载时初始化显示
        window.addEventListener('DOMContentLoaded', () => {
            updateCartDisplay();
        });
        // 本地存储操作
        function saveCartToStorage() {
            try {
                localStorage.setItem('shoppingCart', JSON.stringify(cart));
            } catch (e) {
                console.error('本地存储失败:', e);
                alert('无法保存购物车数据，请检查存储空间');
            }
        }
        function loadCartFromStorage() {
            try {
                const savedCart = localStorage.getItem('shoppingCart');
                return savedCart ? JSON.parse(savedCart) : [];
            } catch (e) {
                console.error('读取存储失败:', e);
                return [];
            }
        }
        // 添加商品事件
        document.querySelectorAll('.add-to-cart').forEach(btn => {
            btn.addEventListener('click', () => {
                const product = {
                    id: btn.dataset.id,
                    name: btn.dataset.name,
                    price: parseFloat(btn.dataset.price),
                    quantity: parseInt(btn.previousElementSibling.value)
                };
                
                const existingItem = cart.find(item => item.id === product.id);
                existingItem ? existingItem.quantity += product.quantity : cart.push(product);
                updateCartDisplay();
                saveCartToStorage();
            });
        });
        // 更新购物车显示
        function updateCartDisplay() {
            const cartItems = document.getElementById('cartItems');
            const totalPrice = cart.reduce((sum, item) => sum + (item.price * item.quantity), 0);
            
            cartItems.innerHTML = cart.map(item => `
                <div class="cart-item" data-id="${item.id}">
                    <div style="flex:2">${item.name}</div>
                    <div style="flex:1">¥${item.price.toFixed(2)}</div>
                    <div style="flex:1">
                        <input type="number" 
                               value="${item.quantity}" 
                               min="1" 
                               class="quantity-update"
                               style="width: 60px">
                    </div>
                    <div style="flex:1">¥${(item.price * item.quantity).toFixed(2)}</div>
                    <button class="btn btn-danger delete-item">删除</button>
                </div>
            `).join('');
            document.getElementById('totalPrice').textContent = totalPrice.toFixed(2);
            saveCartToStorage();
        }
        // 删除商品
        document.getElementById('cartItems').addEventListener('click', (e) => {
            if (e.target.classList.contains('delete-item')) {
                const itemId = e.target.closest('.cart-item').dataset.id;
                cart = cart.filter(item => item.id !== itemId);
                updateCartDisplay();
                saveCartToStorage();
            }
        });
        // 修改数量
        document.getElementById('cartItems').addEventListener('change', (e) => {
            if (e.target.classList.contains('quantity-update')) {
                const itemId = e.target.closest('.cart-item').dataset.id;
                const item = cart.find(item => item.id === itemId);
                item.quantity = parseInt(e.target.value);
                updateCartDisplay();
                saveCartToStorage();
            }
        });
        // 结算功能
        document.getElementById('checkout').addEventListener('click', () => {
            if (cart.length === 0) {
                alert('购物车为空，请先添加商品！');
                return;
            }
            
            const detail = cart.map(item => 
                `${item.name} x${item.quantity} = ¥${(item.price * item.quantity).toFixed(2)}`
            ).join('\n');
            
            if (confirm(`确认结算以下商品：\n${detail}\n总计：¥${document.getElementById('totalPrice').textContent}`)) {
                cart = [];
                localStorage.removeItem('shoppingCart');
                updateCartDisplay();
                alert('结算成功！感谢您的购买！');
            }
        });
    </script>
</body>
</html>